package com.zl.tesseract.scanner.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewStub;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.google.zxing.Result;
import com.zl.tesseract.R;
import com.zl.tesseract.scanner.adapter.MoveResultListAdapter;
import com.zl.tesseract.scanner.beans.MoveBean;
import com.zl.tesseract.scanner.beans.ShelvesBean;
import com.zl.tesseract.scanner.camera.CameraManager;
import com.zl.tesseract.scanner.decode.CaptureMoveActivityHandler;
import com.zl.tesseract.scanner.decode.DecodeManager;
import com.zl.tesseract.scanner.decode.InactivityTimer;
import com.zl.tesseract.scanner.manager.BeepManager;
import com.zl.tesseract.scanner.retrofit.Api;
import com.zl.tesseract.scanner.retrofit.HttpUtil;
import com.zl.tesseract.scanner.retrofit.NetCallBack;
import com.zl.tesseract.scanner.utils.DataUtils;
import com.zl.tesseract.scanner.view.ScannerFinderView;
import com.zl.tesseract.scanner.view.SwipeItemLayout;
import com.zl.tesseract.scanner.views.pickerview.PickerViewUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 移库。
 */
public class MoveActivity extends Activity implements Callback, Camera.ShutterCallback {

    private Context mContext;

    @BindView(R.id.iv_titlebar_left)
    ImageView iv_titlebar_left;
    @BindView(R.id.iv_flash)
    ImageView iv_flash;

    @BindView(R.id.qr_code_view_stub)
    ViewStub qr_code_view_stub;
    @BindView(R.id.qr_code_view_finder)
    ScannerFinderView qr_code_view_finder;
    @BindView(R.id.qr_code_view_background)
    View qr_code_view_background;

    @BindView(R.id.iv_add)
    ImageView iv_add;

    @BindView(R.id.edt_waybill_number)
    EditText edt_waybill_number;
    @BindView(R.id.iv_waybill_number)
    ImageView iv_waybill_number;

    @BindView(R.id.recyclerView_results)
    RecyclerView recyclerView_results;

    @BindView(R.id.tv_select_shelves)
    TextView tv_select_shelves;
    @BindView(R.id.btn_pay)
    Button btn_pay;

    private boolean isQRCode = true;// 是否扫码

    private CaptureMoveActivityHandler mCaptureMoveActivityHandler;
    private boolean mHasSurface;
    private InactivityTimer mInactivityTimer;
    private SurfaceView mSurfaceView;
    private DecodeManager mDecodeManager = new DecodeManager();
    private BeepManager beepManager;

    private Bitmap bmp;


    private MoveResultListAdapter moveResultListAdapter;

    private ArrayList<String> shelvesList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_move);

        ButterKnife.bind(this);
        mContext = this;

        initView();
        initData();

        getShelves();
    }

    private void initView() {
        mHasSurface = false;
    }

    private void initData() {
        mInactivityTimer = new InactivityTimer(this);

        beepManager = new BeepManager(this);
        beepManager.setPlayBeep(true);
        beepManager.setVibrate(true);

        List<MoveBean> moveBeanList = new ArrayList<>();
        moveResultListAdapter = new MoveResultListAdapter(mContext, moveBeanList);
        recyclerView_results.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView_results.setAdapter(moveResultListAdapter);
        recyclerView_results.addOnItemTouchListener(new SwipeItemLayout.OnSwipeItemTouchListener(mContext));
    }

    @OnClick({R.id.iv_titlebar_left, R.id.iv_flash, R.id.iv_add
            , R.id.iv_waybill_number, R.id.tv_select_shelves})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.iv_titlebar_left:
                finish();
                break;
            case R.id.iv_flash:
                if (CameraManager.get().getFlashMode()) {
                    // 开启了闪光灯，应该关闭
                    iv_flash.setImageResource(R.drawable.flash_off);
                    CameraManager.get().setFlashLight(false);
                } else {
                    iv_flash.setImageResource(R.drawable.flash_on);
                    CameraManager.get().setFlashLight(true);
                }
                break;
            case R.id.iv_add:
                // 添加
                if (TextUtils.isEmpty(edt_waybill_number.getText().toString())) {
                    Toast.makeText(mContext, "运单号不能为空", Toast.LENGTH_LONG).show();
                    return;
                }
                if (TextUtils.isEmpty(tv_select_shelves.getText().toString())) {
                    Toast.makeText(mContext, "请选择货架", Toast.LENGTH_LONG).show();
                    return;
                }
                if(tv_select_shelves.getText().toString().equals("选择货架")){
                    Toast.makeText(mContext, "请选择货架", Toast.LENGTH_LONG).show();
                    return;
                }
                MoveBean moveBean = new MoveBean();
                moveBean.setOrder_id(edt_waybill_number.getText().toString());
//                moveBean.setShelve_name(tv_select_shelves.getText().toString());
                moveResultListAdapter.append(moveBean);
                break;
            case R.id.iv_waybill_number:

                break;
            case R.id.tv_select_shelves:
                if(shelvesList == null || shelvesList.size() == 0){
                    return;
                }
                PickerViewUtil.alertBottomWheelOption(mContext, shelvesList, 0,R.string.select_shelves,
                        new PickerViewUtil.OnWheelViewClick() {
                            @Override
                            public void onClick(View view, int postion) {
                                tv_select_shelves.setText(shelvesList.get(postion));
                            }
                        }
                );
                break;
            default:
                break;
        }
    }

    public Rect getCropRect() {
        return qr_code_view_finder.getRect();
    }

    public boolean isQRCode() {
        return isQRCode;
    }

    @Override
    protected void onResume() {
        super.onResume();
        CameraManager.init();
        initCamera();

        beepManager.updatePrefs();
    }

    private void initCamera() {
        if (null == mSurfaceView) {
            qr_code_view_stub.setLayoutResource(R.layout.layout_surface_view);
            mSurfaceView = (SurfaceView) qr_code_view_stub.inflate();
        }
        SurfaceHolder surfaceHolder = mSurfaceView.getHolder();
        if (mHasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            // 防止sdk8的设备初始化预览异常(可去除，本项目最小16)
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
    }

    @Override
    protected void onPause() {
        if (mCaptureMoveActivityHandler != null) {
            try {
                mCaptureMoveActivityHandler.quitSynchronously();
                mCaptureMoveActivityHandler = null;
                if (null != mSurfaceView && !mHasSurface) {
                    mSurfaceView.getHolder().removeCallback(this);
                }
                CameraManager.get().closeDriver();
            } catch (Exception e) {
                // 关闭摄像头失败的情况下,最好退出该Activity,否则下次初始化的时候会显示摄像头已占用.
                finish();
            }
        }

        beepManager.close();

        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (null != mInactivityTimer) {
            mInactivityTimer.shutdown();
        }
        super.onDestroy();
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            if (!CameraManager.get().openDriver(surfaceHolder)) {
                return;
            }
        } catch (IOException e) {
            // 基本不会出现相机不存在的情况
            Toast.makeText(this, getString(R.string.camera_not_found), Toast.LENGTH_SHORT).show();
            finish();
            return;
        } catch (RuntimeException re) {
            re.printStackTrace();
            return;
        }
        qr_code_view_finder.setVisibility(View.VISIBLE);
        qr_code_view_background.setVisibility(View.GONE);
        if (mCaptureMoveActivityHandler == null) {
            mCaptureMoveActivityHandler = new CaptureMoveActivityHandler(this);
        }
    }

    public void restartPreview() {
        if (null != mCaptureMoveActivityHandler) {
            try {
                mCaptureMoveActivityHandler.restartPreviewAndDecode();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!mHasSurface) {
            mHasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mHasSurface = false;
    }

    @Override
    public void onShutter() {
    }

    public Handler getCaptureActivityHandler() {
        return mCaptureMoveActivityHandler;
    }

    /**
     * 获取到扫条形码的结果，处理结果
     * Handler scan result
     *
     * @param result
     */
    public void handleDecode(Result result) {
        mInactivityTimer.onActivity();
        beepManager.playBeepSoundAndVibrate();

        if (null == result) {
            mDecodeManager.showCouldNotReadQrCodeFromScanner(this, new DecodeManager.OnRefreshCameraListener() {
                @Override
                public void refresh() {
                    restartPreview();
                }
            });
        } else {
            handleResult(result);
        }
    }

    /**
     * 获取到扫条形码的结果，处理结果
     * @param result Result
     */
    private void handleResult(Result result) {
        if (TextUtils.isEmpty(result.getText())) {
            mDecodeManager.showCouldNotReadQrCodeFromScanner(this, new DecodeManager.OnRefreshCameraListener() {
                @Override
                public void refresh() {
                    restartPreview();
                }
            });
        } else {
            qrSucceed(result.getText());
        }
    }



    /**
     * 获取到条形码成功，弹窗显示
     * @param result
     */
    private void qrSucceed(final String result) {
        AlertDialog dialog = new AlertDialog.Builder(this).setTitle(R.string.notification)
                .setMessage(result)
                .setPositiveButton(R.string.positive_button_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        restartPreview();

                        edt_waybill_number.setText(result);
                    }
                })
                .show();
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                restartPreview();
            }
        });
    }

    /**
     * 获取货架号
     */
    private void getShelves() {
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("token", "MTU2MTI3OTk4NzE2MzM4Ng");
        HttpUtil.getInstance().getRequestData(Api.GET_GETSHELEVESFROMTOKEN, map, new NetCallBack() {
            @Override
            public void onSuccess(String data) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    List<ShelvesBean> shelvesBeans = DataUtils.getGson().fromJson(jsonObject.getString("data"), new TypeToken<List<ShelvesBean>>() {
                    }.getType());
                    shelvesList = new ArrayList<>();
                    for (ShelvesBean shelvesBean : shelvesBeans) {
                        shelvesList.add(shelvesBean.getSname());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(int code, String message, String data) {
                Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
            }
        });
    }


}